%Code to randomise placement of some object and then to detect the
%placement of it through MLE
%Author: Nathan Rich
clear
clc

x=randi(100); %Randomise Placement
y=randi(100);

for I = 1:10 %Loop to send transmissions with noise
    nx = [(-1)^(randi(2))]*cos(rand()); %noise, with zero mean and some variance
    ny = [(-1)^(randi(2))]*cos(rand()); %^^^^^^^^^ Not sure Why the -1 is here, cos is both negitive and positive  ^^^^^^^^^^^^^^
    X(I) = x + nx; %signals received
    Y(I) = y + ny;
end

%MLE code to detect placement
%==========================================================================
%^^^^^^^^  gaussian white Noise ^^^^^^^^^^^^
% gaussian is f = 1/(sqrt(2*pi*sigma^2)) * exp(-(x-u)^2/(2*sigma^2))
% l = -1/2*n*log(2*pi) - n*log(sigma) - sum(x_i - u)^2 /(2*sigma^2)
% Maximising l then gives, u = sum(X) / n 
%==========================================================================

xMLE = sum(X)/length (X);
yMLE = sum(Y)/length (Y);

xMLEerror = abs(x - xMLE);
yMLEerror = abs(y - yMLE);

fprintf('The error using MLE in the x direction is %d.\nThe error using MLE in the y direction is %d.\n',xMLEerror,yMLEerror)

%Not very useful as this is the same as MoM

%MoM Code to detect placement
xMoM = mean(X);
yMoM = mean(Y);
xMoMerror = abs(x - xMoM);
yMoMerror = abs(y - yMoM);
fprintf('The error using MoM in the x direction is %d.\nThe error using MoM in the y direction is %d.\n',xMoMerror,yMoMerror)

xMoMerrorplot(1) = xMoM; %Setting up arrays for error plot
xMoMerrorplot(2) = x;
yMoMerrorplot(1) = yMoM;
yMoMerrorplot(2) = y;

figure(1)
plot(xMoMerrorplot, yMoMerrorplot, '-o')
title('Error')
xlabel('x')
ylabel('y')
legend('MoM Error')